package com.cn.common.utils.file;

import com.cn.common.utils.text.StringUtil;
import org.apache.commons.lang3.ArrayUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class FileUtil {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    public static final String[] DEFAULT_ALLOWED_EXTENSION = new String[]{"bmp", "gif", "jpg", "jpeg", "png", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", "rar", "zip", "gz", "bz2", "pdf"};
    public FileUtil() {
    }

    public static String getFileType(File file) {
        return null == file ? "" : getFileType(file.getName());
    }

    public static String getFileType(String fileName) {
        int separatorIndex = fileName.lastIndexOf(".");
        return separatorIndex < 0 ? "" : fileName.substring(separatorIndex + 1).toLowerCase();
    }

    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }

            fis = new FileInputStream(file);
            byte[] b = new byte[1024];

            int length;
            while((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException var16) {
            throw var16;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException var15) {
                    var15.printStackTrace();
                }
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }

        }

    }

    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }

        return flag;
    }

    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    public static boolean checkAllowDownload(String resource) {
        if (StringUtil.contains(resource, "..")) {
            return false;
        } else {
            return ArrayUtils.contains(DEFAULT_ALLOWED_EXTENSION, getFileType(resource));
        }
    }

    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        String agent = request.getHeader("USER-AGENT");
        String filename;
        if (agent.contains("MSIE")) {
            filename = URLEncoder.encode(fileName, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            filename = URLEncoder.encode(fileName, "utf-8");
        } else {
            filename = URLEncoder.encode(fileName, "utf-8");
        }

        return filename;
    }

    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=").append(percentEncodedFileName).append(";").append("filename*=").append("utf-8''").append(percentEncodedFileName);
        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    public static byte[] readBytesFromFile(File file) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {
            bytesArray = new byte[(int)file.length()];
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);
        } catch (IOException var12) {
            var12.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException var11) {
                    var11.printStackTrace();
                }
            }

        }

        return bytesArray;
    }

    public static byte[] fileStreamToByte(InputStream inputStream, int size) {
        byte[] bytesArray = null;

        try {
            bytesArray = new byte[size];
            inputStream.read(bytesArray);
        } catch (IOException var12) {
            var12.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException var11) {
                    var11.printStackTrace();
                }
            }

        }

        return bytesArray;
    }
}